package com.aididi.concurrent;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.Executors.*;

/**
 * @Auther: xuzexiang
 * @Date: 2018-10-26 0026 11:32
 * @Description:  Thread1、Thread2、Thread3、Thread4四条线程分别统计C、D、E、F
  *  四个盘的大小，所有线程都统计完毕交给主线程去做汇总，利用CountDownLatch来完成就非常轻松。
 */
public class CountDownLatchDemo {
    /**
     *
     */
    private static CountDownLatch countDownLatch = new CountDownLatch(4);

    /**
     * 线程池
     */
    private static ExecutorService executor = newFixedThreadPool(4);

    /**
     * 开启的线程数
     */
    private static int THREAD_COUNT = 4;

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < THREAD_COUNT; i++) {
            executor.execute(() -> {
                try {
                    // 模拟业务逻辑的耗时
                    int timer = new Random().nextInt(10);
                    System.out.println("随机数："+timer);
                    TimeUnit.SECONDS.sleep(timer);

                    System.out.printf("%s时完成磁盘的统计任务,耗费%d秒.\n", new Date().toString(), timer);
                    // 业务处理完成之后,计数器减一

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                        countDownLatch.countDown();
                }
            });


        }
        System.out.println("countDownLatch数值："+countDownLatch.getCount());
        // 主线程一直被阻塞,直到countDownLatch的值为0
        countDownLatch.await();
        System.out.printf("%s时全部任务都完成,执行合并计算.\n", new Date().toString());
        executor.shutdown();

    }
}
